use std::time::Duration;
use crate::lencrypted;
use crate::lproperties::Properties;
use crate::ltools::lrand;
use crate::ltools::lstring;

// user.id KifZOLwhQ+Rm1NDZGjPnjiYcSUMv0a3xEGqqi4pKO9o=
pub(crate) struct QKeyClient {
    iccid: String,
    iccid_sm3: Vec<u8>,
    phone: String,
    base_url: &'static str,
    properties: Properties,
    sim_index: u32,
    sim_key_total: u32,
}


impl QKeyClient {
    pub(crate) fn new() -> Self {
        QKeyClient {
            iccid: String::new(),
            iccid_sm3: Vec::new(),
            phone: String::new(),
            base_url: "http://222.92.154.166:8099",
            properties: Properties::new(),
            sim_index: 0,
            sim_key_total: 0,
        }
    }

    /* 初始化 */
    pub(crate) async fn qkye_int(&mut self, iccid: String, phone: String, zero_key: String, sim_key_total: u32, file_path: &'static str) {
        self.iccid_sm3 = lencrypted::sm3_encode(&iccid);
        self.iccid = iccid;
        self.phone = phone;
        self.sim_key_total = sim_key_total;

        match self.properties.load(file_path).await {
            Ok(_) => {
                if let Some(key_str_index) = self.properties.get_data(&self.iccid).await {
                    match key_str_index.parse() {
                        Ok(index) => {
                            self.sim_index = index;
                        }
                        Err(_) => {
                            self.sim_index = 1;
                            self.properties.put(self.iccid.clone(), self.sim_index.to_string()).await;
                            self.properties.save().await;
                        }
                    }
                } else {
                    self.sim_index = 1;
                    self.properties.save().await;
                }
            }
            Err(_) => {
                // 加载数据失败
                return;
            }
        }

        /* 生成随机数组 */
        let phone_byte = self.phone.as_bytes();
        let mut buffer = Vec::with_capacity(phone_byte.len() + 9);
        buffer.push(phone_byte.len() as u8);
        buffer.extend_from_slice(phone_byte);
        let mut rand_byte = [0u8; 8];
        lrand::rand_bytes(&mut rand_byte);
        buffer.extend_from_slice(&rand_byte);

        let send_str_sm4 = lencrypted::sm4_gcm_encode(zero_key.as_bytes(), &buffer);
        let send_str = lencrypted::base64_encode_byte_url_safe(&send_str_sm4);

        /* 发送请求 */
        let client = reqwest::Client::new();
        let mut request_builder = client.post(format!("{}/qkey/exchange/login", self.base_url))
            .timeout(Duration::from_secs(5));
        let iccid_encode = lencrypted::base64_encode_byte_standard(&self.iccid_sm3);
        request_builder = request_builder.header("no", iccid_encode);
        let resp = request_builder.send().await.unwrap();
        match resp.text().await {
            Ok(back_data) => {
                // println!("返回数据为： {}", back_data);
                match lencrypted::base64_decode_url_safe_byte(&back_data) {
                    Ok(reslult) => {
                        match lencrypted::sm4_gcm_decode(&zero_key.as_bytes(), &reslult) {
                            Ok(mut res_body) => {
                                res_body.truncate(res_body.len() - 16);
                                let back_phone = lstring::vec_string(&mut res_body);
                                if back_phone == self.phone {
                                    // 返回成功
                                }else {
                                    // 返回失败
                                }
                            }
                            Err(_) => {
                                // 错误处理
                            }
                        }
                    }
                    Err(_) => {
                        // 错误处理
                    }
                }
            }
            Err(e) => {
                // println!("输出失败：{:?}",e);
            }
        }
    }
}



























